package com.caltco.cargo.ops.common.handle;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * @Title: 自动填充基础属性
 * @Description: TODO
 * @Author: yehao
 * @DateTime: 2023/1/12 9:11
 * @return
 * @throws
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入时候的填充策略
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Long userId = (Long) request.getAttribute("userId");
        String realName = (String) request.getAttribute("userName");

        this.setFieldValByName("createAt", new Date(), metaObject);
        this.setFieldValByName("createId", userId, metaObject);
        this.setFieldValByName("createName", realName, metaObject);

        this.setFieldValByName("updateAt", new Date(), metaObject);
        this.setFieldValByName("updateId", userId, metaObject);
        this.setFieldValByName("updateName", realName, metaObject);
    }

    /**
     * 更新时候的填充策略
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Long userId = (Long) request.getAttribute("userId");
        String realName = (String) request.getAttribute("userName");
        this.setFieldValByName("updateAt", new Date(), metaObject);
        this.setFieldValByName("updateId", userId, metaObject);
        this.setFieldValByName("updateName", realName, metaObject);
    }
}
